
package com.lpf.transaction.service;

import com.lpf.transaction.TransactionUtils;
import com.lpf.transaction.dao.UserDao;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private TransactionUtils transactionUtils;

    @Autowired
    private LogService logService;

    /**
     * 功能描述：手动事务
     */
    public void addOfManual() {
        log.error("UserService...addOfManual");
        TransactionStatus transactionStatus = null;
        try {
            transactionStatus = transactionUtils.begin();
            userDao.add("wangWu", 20);
            // int i = 1 / 0;
            transactionUtils.commit(transactionStatus);
        } catch (Exception e) {
            e.printStackTrace();
            transactionUtils.rollback(transactionStatus);
        }
    }

    /**
     * 功能描述：配合AopOfCust使用aop演示事务原理
     */
    public void addOfCustAop() {
        log.error("UserService...addOfCustAop...");
        try {
            userDao.add("wangwu", 20);
            int i = 1 / 0;
        } catch (Exception e) {
            e.printStackTrace();    // 异常在这里自己捕获了，没有抛出去，那么就会执行 proceedingJoinPoint.proceed(); 之后的代码，事务会提交
        }
    }

    /**
     * 功能描述：xml 配置事务
     */
    public void addOfXml() {
        log.error("UserService...addOfXml...");
        userDao.add("wangwu", 20);
        int i = 1 / 0;
    }

    /**
     * 功能描述：注解 配置事物
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void addOfAnnotation() {
        logService.addLog();

        log.error("UserService...addOfAnnotation...");

        userDao.add("wangwu", 20);
        int i = 1 / 0;
    }

    public void setUserDao(UserDao userDao) {
        log.error("setUseDao");
        this.userDao = userDao;
    }
}
